<template>
	<view class="preview">
		<swiper circular :current="currentIndx" @change="changeCurrent">
			<swiper-item v-for="(item, index) in classList" :key="item._id">
				<image v-if="readedImgsIndex.has(index)" @click="maskChange" :src="item.picUrl" mode="aspectFill"></image>
			</swiper-item>
		</swiper>
		<!-- 遮罩层 -->
		<view class="mask" v-show="maskState">
			<!-- #ifndef MP-TOUTIAO -->
				<view class="goBack" :style="{ marginTop: iconMarginTop + getStatusBarHeight() + 'px', marginLeft: getLeftIconWidth() + 'px' }" @click="goBack">
						<uni-icons type="back" size="20" color="#fff"></uni-icons>
				</view>			
			<!-- #endif --> -->
			<view class="count">{{ currentIndx + 1 }} / {{ classList.length }}</view>
			<view class="time"><uni-dateformat :date="new Date()" format="hh:mm"></uni-dateformat></view>
			<view class="data"><uni-dateformat :date="new Date()" format="MM月dd日"></uni-dateformat></view>
			<view class="footer">
				<view class="box" @click="openInfo">
					<uni-icons type="info" size="28"></uni-icons>
					<view class="text">信息</view>
				</view>
				<view class="box" @click="openScore">
					<uni-icons type="star" size="28"></uni-icons>
					<view class="text">{{  classList[currentIndx]?.score }}分</view>
				</view>
				<view class="box">
					<uni-icons type="download" size="28" @click="clickDownload"></uni-icons>
					<view class="text">下载</view>
				</view>
			</view>
		</view>
		<!-- 信息弹出层 -->
		<uni-popup ref="infoPopup" type="bottom" border-radius="30px 30px 0 0" background-color="#fff">
			<view class="popup-info">
				<view class="popup-header">
					<view></view>
					<view class="title">壁纸信息</view>
					<view class="close" @click="closeInfo"><uni-icons type="closeempty" size="20"></uni-icons></view>
				</view>
				
				<scroll-view scroll-y>
					<view class="content">
						<view class="row">
							<view class="label">壁纸ID：</view>
							<text selectable class="value">{{ classList[currentIndx]?.classid }}</text>
						</view>
						
						<view class="row">
							<view class="label">分类：</view>
							<text class="value class">{{ classList[currentIndx]?.classname || classList[currentIndx]?.className }}</text>
						</view>
						
						<view class="row">
							<view class="label">发布者：</view>
							<text class="value">{{ classList[currentIndx]?.nickname }}</text>
						</view>
						
						<view class="row">
							<view class="label">评分：</view>
							<view class="value rate">
								<uni-rate :readonly="true" :value="5" size="16" />						
								<text class="score">{{ classList[currentIndx]?.score }}分</text>
							</view>
						</view>
						
						<view class="row">
							<view class="label">摘要：</view>
							<text class="value">{{ classList[currentIndx]?.description }}</text>
						</view>
						
						<view class="row">
							<view class="label">标签：</view>
							<view class="value tabs">
								<view class="tab" v-for="tab in classList[currentIndx]?.tabs" :key="tab">{{ tab }}</view>
							</view>
						</view>
						
						<view class="copy-right">
							声明：本图片来用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，邮箱2649925181@qq.com，管理将删除侵权壁纸，维护您的权益。
						</view>	
					</view>
				</scroll-view>
			</view>
		</uni-popup>
		<!-- 评分弹出层 -->
		<uni-popup ref="scorePopup" type="center" :is-mask-click="false" border-radius="30rpx" background-color="#fff">
			<view class="popup-score">
				<view class="popup-header">
					<view></view>
					<view class="title">{{ isScore ? '用户已评分' : '壁纸评分' }}</view>
					<view class="close" @click="closeScore"><uni-icons type="closeempty" size="20"></uni-icons></view>
				</view>
				
				<view class="content">
					<uni-rate allow-half :readonly="isScore" v-model="userScore" @change="changeScore" />
					<view class="text">{{ userScore }}分</view>
				</view>
				
				<view class="footer">
					<button type="default" size="mini" plain :disabled="!userScore || isScore" @click="submitScore">确认评分</button>
				</view>
			</view>
		</uni-popup>
		
	</view>
</template>

<script lang="ts" setup>
import { onBeforeMount, ref } from 'vue'
import { onLoad, onShareTimeline, onShareAppMessage } from '@dcloudio/uni-app';
import { getStatusBarHeight, getLeftIconWidth } from '@/utils/system.js'
import { useClassListStore } from '@/stores/class-list.js';
import { scoreAPI, downloadLimitAPI, detailWallAPI } from '@/api/preview.js'
import { handleSaveCurrentImage } from '@/utils/saveImageToAlbum.js'

const classListStore = useClassListStore()
const currentIndx = ref<number>(0)
const currentId = ref<string>(null)
const className = ref<string>(null)
const classList = ref(classListStore.classList)
const readedImgsIndex = ref(new Set())
const isShare = ref(false)


// 切换壁纸
 const changeCurrent = (e: any) => {
	 currentIndx.value = Number(e.detail.current)
	 previewOptimization()
	 // console.log('readedImgsIndex', readedImgsIndex.value);
 }
 
 // 切换壁纸预览优化
 const previewOptimization = () => {
   const len = classList.value.length;
   const current = currentIndx.value;
   
   readedImgsIndex.value.add((current - 1 + len) % len); // 前一个
   readedImgsIndex.value.add(current);                   // 当前
   readedImgsIndex.value.add((current + 1) % len);       // 后一个
 }

// 返回上一页
let iconMarginTop = ref<number>(0)
// #ifdef H5
iconMarginTop.value = 20
// #endif
const goBack = () => {
	isShare.value ? uni.switchTab({ url: '/pages/index/index' }) : uni.navigateBack()
};

// 预览遮罩层
let maskState = ref<boolean>(true)
const maskChange = () => maskState.value = !maskState.value;

// 信息弹出层
const infoPopup = ref(null)
const openInfo = () => infoPopup.value.open();
const closeInfo = () => infoPopup.value.close();

// 评分弹出层
const scorePopup = ref(null)
const isScore = ref(false)
const openScore = () => {
	scorePopup.value.open();
	userScore.value = classList.value[currentIndx.value].userScore ?? 0
	Object.hasOwn(classList.value[currentIndx.value], 'userScore') ? isScore.value = true : isScore.value = false
}

const closeScore = () => {
	userScore.value = 0
	scorePopup.value.close()
};

// 用户评分操作
const userScore = ref<number>(0)
const changeScore = (e: any) => userScore.value = e.value;
const submitScore = async () => {
	const data = {
		classid: classList.value[currentIndx.value].classid,
		wallId: classList.value[currentIndx.value]._id,
		userScore: userScore.value
	}
	uni.showLoading({ title: '加载中' })
	const res = await scoreAPI(data)
	uni.hideLoading()
	
	if(res.errCode === 0) {
		uni.showToast({ title: '评分成功' })
		classListStore.classList[currentIndx.value].userScore = data.userScore
	} else {
		uni.showToast({ title: res.errMsg, icon: 'error' })
	}
	closeScore()
}

// 下载
const clickDownload = async () => {
	// #ifdef WEB
		uni.showModal({
			content: "请长按保存壁纸",
			showCancel: false
		})
	// #endif
	
	// #ifndef WEB
		const params = { 
			classid: classList.value[currentIndx.value].classid, 
			wallId: classList.value[currentIndx.value]._id,
		}
		const res = await downloadLimitAPI(params)
		if(res.errCode !== 0) {
			uni.showToast({
				title: res.errMsg,
				icon: 'none'
			})
			return;
		}
		
		await handleSaveCurrentImage(classList.value[currentIndx.value]?.picUrl);
	// #endif
}

// 分享到消息
onShareAppMessage((e) => {
	return {
		title: `@青冥壁纸`,
		path: `/pages/preview/preview?index=0&id=${currentId.value}&classname=${className.value}`,
	}
})
// 分享到朋友圈
onShareTimeline(() => {
	return {
		title: `@青冥壁纸`,
		query: `index=0&id=${currentId.value}&classname=${className.value}`,
	}
})

// 初始化
onLoad((options) => {
	const { index, id, classname } = options
	currentIndx.value = Number(index)
	currentId.value = id
	className.value = classname
	previewOptimization()
})
 
onBeforeMount(async () => {
	// 点击分享进入页面
	if(currentIndx.value === 0 && currentId.value && classList.value.length === 0) {
		isShare.value = true
		const result = await detailWallAPI({ id: currentId.value })

		// return;
		result.data.map(item => {
			item.className = className.value
			item.picUrl = item.smallPicurl.replace("_small.webp", ".jpg")
		})
		classList.value = result.data;
		classListStore.classList = result.data;
	}
})
</script>

<style lang="scss" scoped>
@import '@/common/style/preview/preview.scss';
</style>
